package cn.edu.neu.springbootdemo.action;

import cn.edu.neu.springbootdemo.core.Constants;
import cn.edu.neu.springbootdemo.model.User;
import cn.edu.neu.springbootdemo.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class LoginAction {
    @Resource(name = "userServiceImpl")
    private UserService userService;
    @RequestMapping("/")
    public String odir(){
        return "forward:/user/home";
    }
    @RequestMapping("/login")
    public String login(User user, HttpSession session, Map<String, String> m) {
        System.out.println("userlogin:" + user.toString());
        User dbUser = userService.existsUser(user);
        if (dbUser != null) {
            session.setAttribute(Constants.LOGIN_USER, dbUser);
            m.put("login", "yes");
            String redirUrl = (String) session.getAttribute(Constants.ORIGINAL_URL);
            if(dbUser.getVip()==0){
                System.out.println("redirUrl:" + redirUrl);
                return "forward:/admin/getUserList" ;
            }else {
                session.setAttribute("user",user);
                return "forward:/user/home";
            }
        } else {
            m.put("login", Constants.LOGIN_ERR);
            return "/login";
        }
    }
    @RequestMapping("/logout")
    public void logout(HttpServletRequest request, HttpServletResponse response){
        System.out.println("++++++++++++++++++++++++++退出登录+++++++++++++++++++++++++++++++");
        request.getSession().invalidate();
        try {
            request.getRequestDispatcher("forward:/login").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
